package com.lu.aio.server;

import cn.hutool.core.util.CharsetUtil;
import com.lu.GlobalConfig;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

/**
 * @program lu-netty
 * @description:
 *  - 信号驱动
 *      - 接收请求，异步io处理(用户态到内核态)，内核态数据准备完毕，发送信号
 *      - 将准备好的数据从内核态复制到用户态，处理逻辑
 *  - aio
 *      - 接收请求，异步io处理(用户态到内核态)，数据准备完毕，将数据复制从内核态复制到用户态，发送信号
 *      - 处理逻辑
 * @author: zhanglu
 * @create: 2022-06-10 17:13:00
 */
@Slf4j
public class AioServer extends Thread{

    private AsynchronousServerSocketChannel serverSocketChannel = null;

    public AsynchronousServerSocketChannel serverSocketChannel(){
        return serverSocketChannel;
    }

    @Override
    public void run() {
        try {
            serverSocketChannel = AsynchronousServerSocketChannel.open(AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 10));
            serverSocketChannel.bind(new InetSocketAddress(GlobalConfig.LOCAL_PORT));
            log.info("AioServer start...");
            //等待异步处理
            CountDownLatch countDownLatch = new CountDownLatch(1);
            //接收连接-处理器
            serverSocketChannel.accept(this, new AioServerChannelInitializer(CharsetUtil.UTF_8));
//            serverSocketChannel.accept(this, new AioServerAcceptCompletionHandler());
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //用户线程
        new AioServer().start();
    }

}
